package com.piece.module.spider.service;

import com.piece.core.jpa.repository.BaseService;
import com.piece.module.spider.expression.ScriptManager;
import com.piece.module.spider.model.Function;
import com.piece.module.spider.response.FunctionRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.script.ScriptEngine;
import java.io.Serializable;

@Slf4j
@Service
@Transactional
public class FunctionService extends BaseService<Function, Long> {

    @Autowired
    private FunctionRepository functionRepository;

    /**
     * 初始化/重置自定义函数
     */
    @PostConstruct
    private void init(){
        try {
            super.setRepository(functionRepository);
            ScriptManager.lock();
            ScriptManager.clearFunctions();
            ScriptEngine engine = ScriptManager.createEngine();
            findAllWithOutStatus().forEach(function -> {
                ScriptManager.registerFunction(engine,function.getName(),function.getParameter(),function.getScript());
            });
            ScriptManager.setScriptEngine(engine);
        } finally {
            ScriptManager.unlock();
        }
    }

    @Override
    public Function insert(Function function) throws Exception {
        return insertOrUpdate(function);
    }

    @Override
    public Function insertOrUpdate(Function function) throws Exception {
        ScriptManager.validScript(function.getName(), function.getParameter(), function.getScript());
        super.insertOrUpdate(function);
        init();
        return function;
    }

    @Override
    public void delete(Serializable id) throws Exception {
        super.delete(id);
        init();
    }
}
